﻿using Clirelmgt.Manager;
using Clirelmgt.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Clirelmgt.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginModel model)
        {
            TempData.Clear();
            Session.Clear();
            bool isvalid = false;
            CRMSessionInfo sessionInfo = new CRMSessionInfo();
            using (CRMDataContext dataContext = new CRMDataContext())
            {
                var result = dataContext.VerifyUser(model.Username.Trim().ToUpperInvariant(), model.Password);
                foreach (var item in result)
                {
                    sessionInfo.UserID = item.UserID;
                    sessionInfo.Username = item.Name;
                    sessionInfo.Language = item.Language;
                    sessionInfo.ModuleAccess = Utility.DeserializeString<ModuleMetadata>(item.AccessXml) as ModuleMetadata;
                    Session["crmsession"] = sessionInfo;
                    isvalid = true;
                }
            }

            if (isvalid)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                TempData["alert"] = "Login failed! Enter valid username and password.";
                return View(model);
            }
        }
    }
}
